package com.behealthy.android;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.xml.parsers.ParserConfigurationException;

import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.behealthy.util.StringUtils;
import com.behealthy.util.Utility;
import com.example.behealthy.R;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.LoginButton;
import com.facebook.android.SessionEvents;
import com.facebook.android.SessionEvents.AuthListener;
import com.facebook.android.SessionEvents.LogoutListener;
import com.facebook.android.SessionStore;

public class BeHealthyWorkoutProfileActivity extends Activity {
	
	//Facebook APP ID
				private static String App_ID = "264163113684409";
	
	// Instance of shared preferences
				String PREFS = "MyPrefs";
				private SharedPreferences sharedPrefs;
				
//				private String url = "http://10.0.2.2:8080/TestDao/WsTest?wsdl";
				private String url = "http://192.168.33.103:8080/TestDao/WsTest?wsdl";
	
	private boolean[] checkedItems;
	private CharSequence[] items;
	private String[] itemsSelected = {"descriere1", "descriere2", "descriere3", "descriere4"};

	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_workout);
        
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        sharedPrefs = getSharedPreferences(PREFS, 0);
        
        
//		Create the Facebook Object using the app id.
    	Utility.mFacebook = new Facebook(App_ID);
//  Instantiate the AsyncRunner object for asynchronous API calls.
    	Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);
    	
    	  
//	    Restore facebook session if one exists
	    SessionStore.restore(Utility.mFacebook, this);
	    SessionEvents.addAuthListener(new FacebookAuthListener());
	    SessionEvents.addLogoutListener(new FacebookLogoutListener());
	    
	    Intent i = getIntent();
	    Boolean bool = i.getBooleanExtra("session", false);
       
        /**
         * Creating all buttons instances
         * */
         
        LoginButton btn_logout = (LoginButton) findViewById(R.id.btnFacebookLogout);
        TextView logout = (TextView) findViewById(R.id.link_to_logout);
        Button next = (Button) findViewById(R.id.btnNext);
        
        final RadioGroup workout = (RadioGroup) findViewById(R.id.profile_workout);
         
        if(bool) {
        	btn_logout.setVisibility(View.VISIBLE);
        	btn_logout.init(this, Utility.mFacebook, true);
        	logout.setVisibility(View.GONE);
        }
        else {
        	btn_logout.setVisibility(View.GONE);
        	logout.setVisibility(View.VISIBLE);
        }
        
     // Listening to logout link
     			logout.setOnClickListener(new Button.OnClickListener() {
     				public void onClick(View v) {
     					// Switching to Login screen
     					Intent i = new Intent(getApplicationContext(),
     							BeHealthyLoginActivity.class);
     					startActivity(i);
     				}
     			});

     // Listening to next link
     			next.setOnClickListener(new Button.OnClickListener() {
     				public void onClick(View v) {
     					
     					int selectedRadio = workout.getCheckedRadioButtonId();
     					RadioButton radio = (RadioButton) findViewById(selectedRadio);
     					String w = (String) radio.getText().toString();
     					     					
     					if(w.equalsIgnoreCase("muscle building")) w = "MB";
     					else if(w.equalsIgnoreCase("toning")) w = "T";
     					else if(w.equalsIgnoreCase("weight loss")) w = "WL";
     					else if(w.equalsIgnoreCase("cross training workouts")) w = "CT";
     					
     					saveDetails(w);
     					
     					String envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
     							+ "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
     							+ "xmlns:ws=\"http://ws.android/\">"
     							+ "<soapenv:Header/>"
     							+ "<soapenv:Body>"
     							+ "<ws:insertProfile>"
     					        + "<account>"
     							+ "<username>%s</username>"
     							+ "<password></password>"
     							+ "<person>"
     							+ "<firstName/>"
     							+ "<lastName></lastName>"
     							+ "<email></email>"
     							+ "<birthDate></birthDate>"
     							+ "</person>"
     							+ "</account>"
     							+ "<gender>%s</gender>"
     							+ "<height>%s</height>"
     							+ "<weight>%s</weight>"
     					        + "<diet>%s</diet>"
     							+ "<workout>%s</workout>"
     							+ "</ws:insertProfile>"
     							+ "</soapenv:Body>"
     							+ "</soapenv:Envelope>";
     					
     							
     					getDetails(envelope);
     							    					               					                            					         					        
     					// Switching to Profile screen
     					Intent i = new Intent(getApplicationContext(),
     							BeHealthyProfileActivity.class);
     					startActivity(i);
     				}
     			});
     			
     // Listening to the on checked radio group event
     	workout.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				
				Toast.makeText(getApplicationContext(), Integer.toString(checkedId), Toast.LENGTH_SHORT).show();
//				Toast.makeText(getApplicationContext(), itemsSelected[checkedId], Toast.LENGTH_SHORT).show();
			}
		});
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_be_healthy_main, menu);
        return true;
    }
    
    public int convertPxtoDip(int pixel){

        float scale = getResources().getDisplayMetrics().density;
        int dips=(int) (pixel/scale);
        Log.d("Dips", Integer.toString(dips));   
        return dips;
    }
    
    public class FacebookAuthListener implements AuthListener {

        public void onAuthSucceed() {
            requestUserData();
        }

        public void onAuthFail(String error) {
//            mText.setText("Login Failed: " + error);
        }
    }
    
//	Callback for fetching current user's name, picture, id.
    
private class UserRequestListener extends BaseRequestListener {

    public void onComplete(final String response, final Object state) {
        JSONObject jsonObject;

        try {
            jsonObject = new JSONObject(response);
            Log.d("JSONResponse", response);
            final String name = jsonObject.getString("name");
            Utility.userUID = jsonObject.getString("id");
//            mUserEmail = jsonObject.getString("email");
            
            final String picURL = "http://graph.facebook.com/"+Utility.userUID+"/picture?type=small";
            Log.d("TAG", picURL);

//            mHandler.post(new Runnable() {
//                public void run() {
//                    mText.setText("Bine ai venit " + name + "!");
//                    mUserPic.setImageBitmap(Utility.getBitmap(picURL));
//                }
//            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
	}

//Request user name, and picture to show on the main screen.

private void requestUserData() {
//	mText.setText("Incarcare nume si poza de profil...");
	Bundle params = new Bundle();
	params.putString("fields", "name, picture, email");
	Utility.mAsyncRunner.request("me", params, new UserRequestListener());
}

public class FacebookLogoutListener implements LogoutListener {
    public void onLogoutBegin() {   
    }

    public void onLogoutFinish() {
    	Intent i = new Intent(getApplicationContext(), BeHealthyLoginActivity.class);
        startActivity(i);	
    }
}

private void logout (){
	Utility.mAsyncRunner.logout(getBaseContext(), new RequestListener() {
		  public void onComplete(String response, Object state) {
			  Intent i = new Intent(getApplicationContext(), BeHealthyLoginActivity.class);
              startActivity(i);
			  
		  }
		  
		  public void onIOException(IOException e, Object state) {}
		  
		  public void onFileNotFoundException(FileNotFoundException e,
		        Object state) {}
		  
		  public void onMalformedURLException(MalformedURLException e,
		        Object state) {}
		  
		  public void onFacebookError(FacebookError e, Object state) {}
		});
}
  

private void saveDetails(String workout) {
	
	Editor e = sharedPrefs.edit();
	e.putString("workout", workout);
	e.commit();
}

private void getDetails(String envelope) {
	
	String username = sharedPrefs.getString("userName", null);
	String gender = sharedPrefs.getString("gender", null);
	String height = sharedPrefs.getString("height", null);
	String weight = sharedPrefs.getString("weight", null);
	String diet = sharedPrefs.getString("diet", null);
	String workout = sharedPrefs.getString("workout", null);
	
	
	String requestEnvelope = String.format(envelope, 
		username, gender, height, weight, diet, workout);
		
	String soapAction = "insertProfile";
	String response = "message";

	response = Utility.CallWebService(url, soapAction,
			requestEnvelope); 
	
	String s = "";
	try {
		s = Utility.parseByDOM(response, "insertProfileResponse");
	} catch (ParserConfigurationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (SAXException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
	
	if(s.equals("true")) alertDialog.setMessage(StringUtils.SUCCESS_REGISTER);
	else alertDialog.setMessage(StringUtils.ERR_REGISTER);
	
	alertDialog.setButton("OK",
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,
						int which) {

				}
			});
	alertDialog.show();
}
}
